<template>

  <el-container>
    <!-- <el-header>Header</el-header> -->
    <el-main>
      <!-- <el-card class="box-card"> -->
      <div slot="header" class="pageheader">
        <!-- <el-badge :value="ChargeCount" class="item">
          <el-tag type="info" effect="dark"> 护士工作量</el-tag>
        </el-badge> -->
        <div style="margin-left: 20px;">
          <div class="block">
            <!-- <el-button  type="success" @click="canDO=true" width="120px" :disabled="canDO">月份</el-button> -->
            <el-button type="primary" icon="Edit" circle @click="canDO = true" :disabled="canDO" />
            <el-date-picker v-model="chooseDate" type="month" placeholder="选择月份" :disabled="!canDO" />

            <el-button type="primary" @click="SearchHandle">查询</el-button>
            <span>
              <el-button icon="Plus" type="success" @click="Addhandle" :disabled="canDO">添加</el-button>
              <el-button :icon="Printer" type="warning" @click="exportCurPage" :disabled="canDO">导出excel</el-button>

              <el-button :icon="Printer" type="warning" @click="handlePrint" :disabled="canDO">打印pdf</el-button>
            </span>

          </div>
        </div>

      </div>
      <div class="home">
        <!-- 请求信息 -->

        <!-- 数据列表 -->
        <el-row :gutter="20">
          <el-col :span="24">

            <el-table :data="WorkList" id="out-table" style="width: 100%; " :height="tableHeight" stripe
              :summary-method="getSummaries" show-summary>

              <el-table-column prop="RECORD_TIME" fixed="left" :formatter="dateFormatter" label="日期" width="120">
              </el-table-column>
              <el-table-column v-for="(item, index) in ColList" :prop="item.FieldName" width="80">
                <template #header>
                  <div class="headstr">
                    {{ item.Header }}
                  </div>
                </template>
              </el-table-column>

              <!-- <el-table-column fixed type="selection" width="55"> </el-table-column> -->

              <!-- <el-table-column prop="C1" label="总数" width="80"> </el-table-column>
              <el-table-column prop="C2" label="入院" width="80"> </el-table-column>
              <el-table-column prop="C3" label="出院" width="80"> </el-table-column>
              <el-table-column prop="C5" label="一级护理" width="80"> </el-table-column>
              <el-table-column prop="C6" width="80">
                <template #header>
                  <div class="headstr">
                    静脉输液<br>
                  </div>
                </template>
              </el-table-column>
              <el-table-column prop="C7" width="80">
                <template #header>
                  <div class="headstr">
                    肌肉注射<br>
                  </div>
                </template>
              </el-table-column>
              <el-table-column prop="C8" width="80">
                <template #header>
                  <div class="headstr">
                    皮试<br>
                  </div>
                </template>
              </el-table-column>
              <el-table-column prop="C9" width="80">
                <template #header>
                  <div class="headstr">
                    抽血<br>
                  </div>
                </template>
              </el-table-column>

              <el-table-column prop="C11" width="80">
                <template #header>
                  <div class="headstr">
                    鼻饲<br>
                  </div>
                </template>
              </el-table-column>
              <el-table-column prop="C12" width="80">

                <template #header>
                  <div class="headstr">
                    皮下<br>
                  </div>
                </template>
              </el-table-column>
              <el-table-column prop="C13" width="80">

                <template #header>
                  <div class="headstr">
                    雾化<br>
                  </div>
                </template>
              </el-table-column>
              <el-table-column prop="C14" width="80">
                <template #header>
                  <div class="headstr">
                    血糖<br>
                  </div>
                </template>

              </el-table-column>
              <el-table-column prop="C15" width="80">
                <template #header>
                  <div class="headstr">
                    吸氧<br>
                  </div>
                </template>
              </el-table-column>
              <el-table-column prop="C16" width="80">
                <template #header>
                  <div class="headstr">
                    灌肠<br>

                  </div>
                </template>

              </el-table-column>
              <el-table-column prop="C17" label="订单号" width="80">
                <template #header>
                  <div class="headstr">
                    约束<br>

                  </div>
                </template>

              </el-table-column>

              <el-table-column prop="C10" width="90">
                <template #header>
                  <div class="headstr">
                    X射线检查<br>

                  </div>
                </template>
              </el-table-column>

              <el-table-column prop="C18" width="90">
                <template #header>
                  <div class="headstr">
                    B超<br>
                  </div>
                </template>
              </el-table-column>
              <el-table-column prop="C19" width="90">
                <template #header>
                  <div class="headstr">
                    心电图<br>

                  </div>
                </template>
              </el-table-column>

              <el-table-column prop="C4" label="抢救" width="80"> </el-table-column>
              <el-table-column prop="C20" label="特护" width="80"> </el-table-column>
              <el-table-column prop="C21" label="胃管" width="80"> </el-table-column>
              <el-table-column prop="C22" label="导尿" width="80"> </el-table-column>
              <el-table-column prop="C23" label="尿常规" width="80"> </el-table-column>
              <el-table-column prop="C24" label="便常规" width="80"> </el-table-column>
              <el-table-column prop="C25" label="脑电图" width="80"> </el-table-column> -->


              <el-table-column align="right" fixed="left" width="80">
                <template #header>
                  <div class="headstr">
                    操作
                  </div>
                </template>
                <template #default="scope">
                  <el-button type="primary" size="small" @click="handleEdit(scope.$index, scope.row)">
                    修改
                  </el-button>

                </template>
              </el-table-column>
            </el-table>

          </el-col>
        </el-row>

      </div>
      <!-- </el-card> -->

    </el-main>
    <!-- <el-footer>
      <div class="footer-area">

      </div>
    </el-footer> -->
    <!-- <div class="bottomGroup">
    
      <el-row :gutter="20">
        <el-col :span="24">
          <el-button icon="el-icon-s-open" @click="Refresh">刷新</el-button>

        </el-col>
      </el-row>
    </div> -->
  </el-container>


  <!-- 新增对话框 -->
  <el-dialog v-model="dialogFormVisible" width="95%" title="添加记录">
    <el-form :model="AddModel" label-width="100px" label-position="right">
      <el-row>
        <el-col :span="12">
          <el-form-item label="日期:">
            <el-date-picker :disabled-date="disabledDate" v-model="AddModel.RECORD_TIME" type="date" placeholder="日期" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>


        <el-col v-for="(item, index) in ColList" :span="ColSpaceNum">
          <el-form-item :label="item.Header + ':'">
            <el-input v-model="AddModel[item.FieldName]" />
          </el-form-item>
        </el-col>
        <!-- <el-col :span="8">
          <el-form-item label="入院:">
            <el-input v-model="AddModel.C2" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="出院:">
            <el-input v-model="AddModel.C3" />
          </el-form-item>
        </el-col>



        <el-col :span="8">
          <el-form-item label="一级护理:">
            <el-input v-model="AddModel.C5" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="静脉输液:">
            <el-input v-model="AddModel.C6" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="肌肉注射:">
            <el-input v-model="AddModel.C7" />
          </el-form-item>
        </el-col>



        <el-col :span="8">
          <el-form-item label="皮试:">
            <el-input v-model="AddModel.C8" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="抽血:">
            <el-input v-model="AddModel.C9" />
          </el-form-item>
        </el-col>




        <el-col :span="8">
          <el-form-item label="鼻饲:">
            <el-input v-model="AddModel.C11" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="皮下:">
            <el-input v-model="AddModel.C12" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="雾化:">
            <el-input v-model="AddModel.C13" />
          </el-form-item>
        </el-col>



        <el-col :span="8">
          <el-form-item label="血糖:">
            <el-input v-model="AddModel.C14" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="吸氧:">
            <el-input v-model="AddModel.C15" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="灌肠:">
            <el-input v-model="AddModel.C16" />
          </el-form-item>
        </el-col>



        <el-col :span="8">
          <el-form-item label="约束:">
            <el-input v-model="AddModel.C17" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="X射线检查:">
            <el-input v-model="AddModel.C10" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="B超:">
            <el-input v-model="AddModel.C18" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="心电图:">
            <el-input v-model="AddModel.C19" />
          </el-form-item>
        </el-col>



        <el-col :span="8">
          <el-form-item label="抢救:">
            <el-input v-model="AddModel.C4" />
          </el-form-item>
        </el-col>

        <el-col :span="8">
          <el-form-item label="特护:">
            <el-input v-model="AddModel.C20" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="胃管:">
            <el-input v-model="AddModel.C21" />
          </el-form-item>
        </el-col>



        <el-col :span="8">
          <el-form-item label="导尿:">
            <el-input v-model="AddModel.C22" />
          </el-form-item>
        </el-col>

        <el-col :span="8">
          <el-form-item label="尿常规:">
            <el-input v-model="AddModel.C23" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="便常规:">
            <el-input v-model="AddModel.C24" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="便常规:">
            <el-input v-model="AddModel.C25" />
          </el-form-item>
        </el-col> -->

      </el-row>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button type="primary" @click="SaveHandle">确定</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
import FileSaver from 'file-saver'
import * as XLSX from 'xlsx'
import dayjs from "dayjs";
import { reactive, toRefs, ref, getCurrentInstance, watch, onMounted, toRaw, watchEffect } from "vue";

//组件
import { ElMessage, ElNotification } from "element-plus"
//Api
//import NurseAPI { GetNurseDayWorksByMouth, GetNurseDayWorkById, SaveNurseDayWork } from "@/api/nurse";
import NurseAPI from "@/api/nurse";
// 选择月份
const chooseDate = ref('')

// 导出当前页
const exportCurPage = () => {
  //route.meta.title
  let name = '护士工作量统计';

  var wb = XLSX.utils.table_to_book(document.querySelector('#out-table'), { sheet: name, raw: true })
  console.log(wb)
  var wbout = XLSX.write(wb, { bookType: 'xlsx', bookSST: true, type: 'array' })
  try {
    FileSaver.saveAs(new Blob([wbout], { type: 'application/octet-stream' }), `${name}.xlsx`)
  } catch (e) { if (typeof console !== 'undefined') console.log(e, wbout) }
  return wbout
}

// 只能选择本月的日期
const disabledDate = (time) => {
  // 获取当前月份
  let dt1 = dayjs(chooseDate.value).format('YYYY-MM');

  let dt2 = dayjs(time).format('YYYY-MM')
  return dt1 !== dt2
}
//可操作记录
const canDO = ref(false)

//新建弹出框显示隐藏
const dialogFormVisible = ref(false)
//新建按钮
function Addhandle() {
  let data = { "ID": 0, "SID": "0", "RECORD_TIME": null, "GROUPNAME": "", "CREATE_TIME": null, "C1": "", "C2": "", "C3": "", "C4": "", "C5": "", "C6": "", "C7": "", "C8": "", "C9": "", "C10": "", "C11": "", "C12": "", "C13": "", "C14": "", "C15": "", "C16": "", "C17": "", "C18": "", "C19": "", "C20": "", "C21": null, "C22": null, "C23": null, "C24": null, "C25": null };
  data.RECORD_TIME = chooseDate.value;
  data.DATE_TIME = dayjs()
  AddModel.value = data;
  dialogFormVisible.value = true;
}
//提示成功
const showSuccess = () => {
  ElNotification({
    title: '成功',
    message: '操作成功',
    type: 'success',
  })
}
//提示失败
const showFail = (msg) => {
  ElNotification({
    title: '失败',
    message: msg,
    type: 'error',
  })
}
//修改按钮
function handleEdit(i, b) {
  // 取出原始对象
  const m = toRaw(b);
  console.log(m.SID);
  var parm = { id: m.SID };

  NurseAPI.GetNurseDayWorkById(parm).then((res) => {
    AddModel.value = res;
    //弹出添加界面
    dialogFormVisible.value = true;
  }).catch((msg) => {
    showFail(msg);
  }).finally(() => {

  });
}

const ColList = ref([]);

//添加实体
const AddModel = ref({});
//列表
const WorkList = ref([]);

//点击打印
function handlePrint() {
  let dt1 = dayjs(chooseDate.value).format('YYYY-MM');
  let url2 = import.meta.env.VITE_APP_BASE_API + '/api/Print/PrintPdf?id=ONE|' + dt1;
  console.log(url2)
  window.open(url2, '_self');
}

//点击搜索
function SearchHandle() {
  canDO.value = false;
  let dt = dayjs(chooseDate.value).format('YYYY-MM');
  console.log(dt);
  var parm = { mouth: dt };
  console.log(parm)
  NurseAPI.GetNurseDayWorksByMouth(parm).then((res) => {
    console.log("查询成功");
    WorkList.value = res;
  }).catch(() => {

  }).finally(() => {

  });
}

const ColSpaceNum = ref(6);

//获取列配置

function GetColList() {
  var parm = {};
  NurseAPI.GetDictCol(parm).then((res) => {
    console.log("查询成功");
    console.log(res);
    ColList.value = res;
  }).catch(() => {

  }).finally(() => {

  });

}

//保存
function SaveHandle() {
  const pdata = toRaw(AddModel.value);
  if (pdata.RECORD_TIME instanceof Object) {
    //添加日期转字符串
    pdata.RECORD_TIME = dayjs(pdata.RECORD_TIME).format('YYYY-MM-DD');
    console.log(pdata.RECORD_TIME);
  }

  NurseAPI.SaveNurseDayWork(pdata).then((res) => {
    showSuccess();
    dialogFormVisible.value = false;
    SearchHandle();
  }).catch((msg) => {
    showFail(msg);
  });
}
//合计
const getSummaries = (param) => {
  const { columns, data } = param
  const sums = []
  columns.forEach((column, index) => {

    if (index === 0) {
      sums[index] = '合计:'
      return
    }

    if (index === 1) {
      sums[index] = ''
      return
    }


    const values = data.map((item) => Number(item[column.property]))
    if (!values.every((value) => Number.isNaN(value))) {
      sums[index] = `${values.reduce((prev, curr) => {
        const value = Number(curr)
        if (!Number.isNaN(value)) {
          return prev + curr
        } else {
          return prev
        }
      }, 0)}`
    } else {
      sums[index] = ''
    }

  })

  return sums
}
const tableHeight = ref(800);
//获取表格高度
const getTableHeight = () => {
  const tableH = 90; //距离页面下方的高度
  const tableHeightDetil = window.innerHeight - tableH;
  if (tableHeightDetil <= 300) {
    tableHeight.value = 300;
  } else {
    tableHeight.value = window.innerHeight - tableH;
  }
};

function dateFormatter(row, column) {

  let datetime = row.RECORD_TIME;
  if (datetime) {
    datetime = new Date(datetime);
    let y = datetime.getFullYear() + '-';
    let mon = datetime.getMonth() + 1 + '-';
    let d = datetime.getDate();
    return y + mon + d;
  }
  return ''
}

// 监听窗口变化动态设置表格高度
window.onresize = () => {
  getTableHeight()
}

//挂载完毕
onMounted(() => {
  getTableHeight()
  // watchEffect(() => {
  //   const windowHeight = window.innerHeight;
  //   // 这里可以执行你需要的操作，比如更新数据或者调用方法
  //   console.log(`屏幕高度变化了，现在是：${windowHeight}px`);
  // });

  if (window.innerWidth <= 568)
    ColSpaceNum.value = 24
  if (window.innerWidth <= 912)
    ColSpaceNum.value = 12
  else if (window.innerWidth <= 1024)
    ColSpaceNum.value = 8
  else if (window.innerWidth <= 1624)
    ColSpaceNum.value = 6
  GetColList();
  //当天日期
  let dtStr = dayjs().format('YYYY-MM');
  let df = dayjs(dtStr);
  chooseDate.value = df;
  SearchHandle();


})

</script>

<style scoped lang="scss">
.pageheader {
  display: flex;
  flex-direction: row;
  justify-items: flex-start;
  vertical-align: middle;
  align-items: center;
}

.bottomGroup {
  position: fixed;
  z-index: 999;
  bottom: 0px;
  left: 0px;
  width: 100%;
  overflow: hidden;
  background-color: grey;
  color: white;
  border-radius: 5px;
  display: flex;
  flex-direction: column;
  justify-content: space-around;
  align-items: center;
  height: 60px;
  padding: 20px;
  margin: 0px 2px;
  box-sizing: border-box;
}

.footer-area {
  height: 10px;
}

.box-card {
  padding: 0px;
  margin: 0px;
}

.headstr {
  text-align: center;
}
</style>